<script setup lang="tsx">
import { computed, reactive, ref, watch } from 'vue';
import type { SelectOption } from 'naive-ui';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import { $t } from '@/locales';
import type { SmsTemplate, SmsTemplateEditAndCreateParams } from '@/service/api';
import { createSmsTemplate, fetchSmsChannelOptions, updateSmsTemplate } from '@/service/api';
import { DICT_TYPE, getDictLabel, getIntDictOptions } from '@/utils/dict';

defineOptions({
  name: 'SmsTemplateOperateModal'
});

export type OperateType = NaiveUI.TableOperateType;

interface Props {
  /** the type of operation */
  operateType: OperateType;
  /** the edit menu data or the parent menu data when adding a child menu */
  rowData?: SmsTemplate | null;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const { formRef, validate, restoreValidation } = useNaiveForm();
const { defaultRequiredRule } = useFormRules();
const submitLoading = ref(false);

let channelIdOptions: any = [];

const title = computed(() => {
  const titles: Record<OperateType, string> = {
    add: $t('page.base.sms.template.add'),
    edit: $t('page.base.sms.template.edit')
  };
  return titles[props.operateType];
});

type Model = Pick<
  SmsTemplateEditAndCreateParams,
  'type' | 'status' | 'code' | 'name' | 'content' | 'remark' | 'apiTemplateId' | 'channelId' | 'channelCode'
> & {
  id: number | null;
};

const model: Model = reactive(createDefaultModel());

function createDefaultModel(): Model {
  return {
    id: null,
    type: null,
    code: '',
    status: 1,
    name: '',
    content: '',
    remark: '',
    apiTemplateId: '',
    channelId: null,
    channelCode: ''
  };
}

type RuleKey = Extract<keyof Model, 'type' | 'status' | 'code' | 'name' | 'content' | 'apiTemplateId' | 'channelId'>;

const rules: Record<RuleKey, App.Global.FormRule> = {
  type: defaultRequiredRule,
  status: defaultRequiredRule,
  code: defaultRequiredRule,
  name: defaultRequiredRule,
  content: defaultRequiredRule,
  apiTemplateId: defaultRequiredRule,
  channelId: defaultRequiredRule
};

function closeDrawer() {
  submitLoading.value = false;
  visible.value = false;
}

async function handleSubmit() {
  await validate();

  submitLoading.value = true;
  if (props.operateType === 'edit') {
    // request
    const { error } = await updateSmsTemplate(model.id as number, model);

    if (!error) {
      window.$message?.success($t('common.updateSuccess'));
      closeDrawer();
      emit('submitted');
    }
  } else {
    const { error } = await createSmsTemplate(model);
    if (!error) {
      window.$message?.success($t('common.addSuccess'));
      closeDrawer();
      emit('submitted');
    }
  }
}

async function handleInitModel() {
  channelIdOptions = [];
  Object.assign(model, createDefaultModel());

  // 加载渠道列表
  const { data: res } = await fetchSmsChannelOptions();
  res?.forEach(item => {
    channelIdOptions.push({
      label: item.label,
      value: item.value,
      extra: item.extra
    });
  });

  if (!props.rowData) return;

  if (props.operateType === 'edit' && props.rowData) {
    Object.assign(model, props.rowData);
  }
}

watch(visible, () => {
  if (visible.value) {
    handleInitModel();
    restoreValidation();
  }
});

const channelIdRenderLabel = (option: SelectOption) => {
  return `${option.extra}【 ${getDictLabel(DICT_TYPE.SYSTEM_SMS_CHANNEL_CODE, option.label)}】`;
};
</script>

<template>
  <NModal v-model:show="visible" :title="title" preset="card" :mask-closable="false" class="w-250">
    <NScrollbar class="max-h-200 pr-20px">
      <NForm ref="formRef" :model="model" :rules="rules" label-placement="left" label-width="auto">
        <NFormItem :label="$t('page.base.sms.template.channelId')" path="channelId">
          <NSelect
            v-model:value="model.channelId"
            :options="channelIdOptions"
            :render-label="channelIdRenderLabel"
            clearable
            :placeholder="$t('page.base.sms.template.form.channelCode')"
          />
        </NFormItem>
        <NFormItem :label="$t('page.base.sms.template.type')" path="type">
          <NSelect
            v-model:value="model.type"
            :options="getIntDictOptions(DICT_TYPE.SYSTEM_SMS_TEMPLATE_TYPE)"
            clearable
            :placeholder="$t('page.base.sms.template.form.type')"
          />
        </NFormItem>
        <!-- 在后台进行生成 -->
        <!--
 <NFormItem :label="$t('page.base.sms.template.code')" path="code">
          <NInput v-model:value="model.code" :placeholder="$t('page.base.sms.template.form.code')" />
        </NFormItem> 
-->
        <NFormItem :label="$t('page.base.sms.template.name')" path="name">
          <NInput v-model:value="model.name" :placeholder="$t('page.base.sms.template.form.name')" />
        </NFormItem>
        <NFormItem :label="$t('page.base.sms.template.content')" path="content">
          <NInput
            v-model:value="model.content"
            type="textarea"
            :placeholder="$t('page.base.sms.template.form.content')"
          />
        </NFormItem>
        <NFormItem :label="$t('page.base.sms.template.status')" path="status">
          <NRadioGroup v-model:value="model.status">
            <NRadio
              v-for="item in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
              :key="item.value"
              :value="item.value"
              :label="item.label"
            />
          </NRadioGroup>
        </NFormItem>
        <NFormItem :label="$t('page.base.sms.template.apiTemplateId')" path="apiTemplateId">
          <NInput v-model:value="model.apiTemplateId" :placeholder="$t('page.base.sms.template.form.apiTemplateId')" />
        </NFormItem>
        <NFormItem :label="$t('page.base.sms.template.remark')" path="remark">
          <NInput
            v-model:value="model.remark"
            type="textarea"
            :placeholder="$t('page.base.sms.template.form.remark')"
          />
        </NFormItem>
      </NForm>
    </NScrollbar>
    <template #footer>
      <NSpace justify="end" :size="16">
        <NButton @click="closeDrawer">{{ $t('common.cancel') }}</NButton>
        <NButton type="primary" :loading="submitLoading" @click="handleSubmit">{{ $t('common.confirm') }}</NButton>
      </NSpace>
    </template>
  </NModal>
</template>

<style scoped>
.flex-end {
  display: flex;
  justify-content: flex-end;
}
</style>
